<?php

namespace App\Models\V5;

use Illuminate\Database\Eloquent\Model;
use DB;

class ScoreModel extends Model
{

    protected $table        = 'score';

    public function add_score($userId,$contentId,$contentType,$score)
    {
        $scoreInfo  = $this->get_score($userId,$contentId,$contentType);

        if($scoreInfo)
        {
            $this->where('id',$scoreInfo->id)->update(['score'=>$score]);
        }else{
            $this->score        = $score;
            $this->user_id      = $userId;
            $this->content_id   = $contentId;
            $this->content_type = $contentType;
            $this->save();
        }
        return true;
    }


    /**
     * 获得评分
     * */
    public function get_score($userId,$contentId,$contentType)
    {
        return $this->where('user_id',$userId)
            ->where('content_id',$contentId)
            ->where('content_type',$contentType)
            ->first();
    }


    /**
     * 获得平均分数
     * */
    public function get_average_score($contentId,$contentType)
    {
        $sql    = "SELECT count(id) as total ,sum(score)  score FROM score
                    WHERE content_id = $contentId
                    AND   content_type = '$contentType' ";

        $info   = DB::select($sql);
        $info   = $info ? $info[0] : null;
        return $info;
    }
}
